<template>
	<!-- 优惠券 -->
	<div class="counpon_container">
		<div class="counpon_section">
			<div class="counpon_header">
				<el-input style="width: 200px;" clearable v-model="searList.title" placeholder="请输入优惠券标题"></el-input>
				<el-select v-model="searList.type" clearable style="width: 200px" placeholder="请选择优惠券类型">
					<el-option v-for="(item,index) in couponType" :key="index" :label="item.name" :value="item.value" />
				</el-select>
				<el-select clearable v-model="searList.status" style="width: 200px" placeholder="请选择优惠券状态">
					<el-option v-for="(item,index) in couponStatus" :key="index" :label="item.name" :value="item.value" />
				</el-select>
				<el-button type="primary" icon="el-icon-search" @click='search()'>查找</el-button>
				<el-button type="primary" icon="el-icon-edit" @click='fixCoupon("add")'>添加</el-button>
				<el-button type="primary" icon="el-icon-download" @click='download()'>当前页导出</el-button>
			</div>
			<!-- 优惠券数据 -->
			<el-scrollbar>
				<!-- <div class="scroll"> -->
				<el-table v-loading="loading" :data="couponList" size="small" element-loading-text="正在查询中。。。" border fit
				 highlight-current-row style="overflow-x: auto;">
					<el-table-column align="center" label="优惠券ID" prop="id" sortable />
					<el-table-column align="center" label="优惠券名称" prop="title" />
					<el-table-column align="center" label="优惠券类型" prop="type">
						<template slot-scope="scope">{{couponType[scope.row.type - 1].name}}</template>
					</el-table-column>
					<el-table-column align="center" label="介绍" prop="description" />
					<el-table-column align="center" label="优惠券数量" prop="total">
						<template slot-scope="scope">{{scope.row.total}}</template>
					</el-table-column>
					<el-table-column align="center" label="剩余数量" prop="surplus">
						<template slot-scope="scope">{{scope.row.surplus >= 0 ? scope.row.surplus : "不限"}}</template>
					</el-table-column>
					<el-table-column align="center" label="每人限领" prop="limit">
						<template slot-scope="scope">{{scope.row.limit >= 0 ? scope.row.limit : "不限" }}</template>
					</el-table-column>
					<el-table-column align="center" label="满减金额" prop="discount">
						<template slot-scope="scope">减免{{ scope.row.discount }}元</template>
					</el-table-column>
					<el-table-column align="center" label="最低消费" prop="min">
						<template slot-scope="scope">满{{ scope.row.min }}元可用</template>
					</el-table-column>
					<el-table-column align="center" label="状态" prop="status">
						<template slot-scope="scope">
							<el-tag>{{ statusFitlters(scope.row.status) }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column align="center" label="使用类目名称" prop="categoryTitle" width="100">
						<template slot-scope="scope">
							<el-tag>{{scope.row.categoryTitle? scope.row.categoryTitle: "全部类目"}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column v-show="false" align="center" label="使用类目ID" prop="categoryId" width="100" />
					<el-table-column align="center" label="领券相对天数" prop="days">
						<template slot-scope="scope">{{scope.row.days? scope.row.days : "无"}}</template>
					</el-table-column>
					<el-table-column align="center" label="领券开始时间" prop="gmtStart">
						<template slot-scope="scope">{{startTime(scope.row.gmtStart)}}</template>
					</el-table-column>
					<el-table-column align="center" label="领券结束时间" prop="gmtEnd">
						<template slot-scope="scope">{{endTime(scope.row.gmtEnd)}}</template>
					</el-table-column>
					<el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
						<template slot-scope="scope">
							<el-button type="primary" size="mini" @click='setStatus(scope.row)'>{{ statusBtn(scope.row.status) }}</el-button>
							<el-button type="primary" size="mini" @click='fixCoupon("edit",scope.row)'>编辑</el-button>
							<el-button type="danger" size="mini" @click='delCoupon(scope.row)'>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- </div> -->
			</el-scrollbar>
			<!-- 添加或修改对话框 -->
			<el-dialog :title="title" :visible.sync="dialogVisible">
				<el-form ref="couponForm" :rules="rules" :model="couponForm" status-icon label-position="left" label-width="100px"
				 style="width: 400px; margin-left:50px;">
					<el-form-item label="优惠券名称" prop="title">
						<el-input v-model="couponForm.title" />
					</el-form-item>
					<el-form-item label="优惠卷类型" prop="type">
						<el-select v-model="couponForm.type">
							<el-option v-for="(item, index) in couponTypeOptions" :key="index" :label="item.name" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="介绍" prop="description">
						<el-input v-model="couponForm.description" />
					</el-form-item>
					<el-form-item label="优惠券数量" prop="total">
						<el-input v-model="couponForm.total">
							<template slot="append">张</template>
						</el-input>
					</el-form-item>
					<el-form-item label="每人限领" prop="limit">
						<el-input v-model="couponForm.limit">
							<template slot="append">张</template>
						</el-input>
					</el-form-item>
					<el-form-item label="满减金额" prop="discount">
						<el-input v-model="couponForm.discount">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
					<el-form-item label="最低消费" prop="min">
						<el-input v-model="couponForm.min">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
					<el-form-item label="优惠卷状态" prop="status">
						<el-select v-model="couponForm.status">
							<el-option v-for="(item, index) in couponStatusOptions" :key="index" :label="item.name" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="有效期">
						<el-radio-group v-model="couponForm.timeType">
							<el-radio-button :label="0">领券相对天数</el-radio-button>
							<el-radio-button :label="1">指定绝对时间</el-radio-button>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-show="couponForm.timeType === 0" prop="days">
						<el-input v-model="couponForm.days" style="margin-left: 100px;">
							<template slot="append">天</template>
						</el-input>
					</el-form-item>
					<el-form-item v-show="couponForm.timeType === 1" prop="time" style="margin-left: 100px;">
						<!-- 时间选择器 -->
						<el-date-picker v-model="couponForm.gmtStart" type="datetime" placeholder="选择日期" style="width: 46%;" />
						<span class="line">至</span>
						<el-date-picker v-model="couponForm.gmtEnd" type="datetime" placeholder="选择日期" style="width: 46%;" />
					</el-form-item>
					<el-form-item label="商品限制范围">
						<el-radio-group :disabled="title === '查看'" v-model="couponForm.goodsType">
							<el-radio-button :label="0">全场通用</el-radio-button>
							<el-radio-button :label="1">指定分类</el-radio-button>
						</el-radio-group>
					</el-form-item>
					<el-form-item v-if="title === '查看'" v-show="couponForm.goodsType === 1" label="优惠类目">
						<el-input v-model="couponForm.categoryTitle" :disabled="title === '查看'" />
					</el-form-item>
					<el-form-item v-if="title === '创建'" v-show="couponForm.goodsType === 1" label="优惠类目">
						<el-cascader v-model="couponForm.categoryTitle" :options="categoryOptions" :props="{ checkStrictly: true }"
						 placeholder="优惠类目" filterable />
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeDialog()">取消</el-button>
					<el-button v-if="title == '创建'" type="primary" @click="addCoupon('couponForm')">确定</el-button>
					<el-button v-else type="primary" @click="updateData('couponForm')">确定</el-button>
				</div>
			</el-dialog>
			<!-- 分页 -->
			<el-footer v-if="couponList.length>0" class="border-top d-flex align-items-center px-0  bg-white" style="margin-top: 36px;">
				<div style="flex: 1;" class="px-2">
					<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="searList.pageNo"
					 :page-sizes="[10, 20, 30, 50, 100]" :page-size="searList.limit" layout="total, sizes, prev, pager, next, jumper"
					 :total="total">
					</el-pagination>
				</div>
			</el-footer>
		</div>
	</div>
</template>

<script>
	import {
		getCoupon,
		setCouponStatus,
		deleteCoupon,
		getCategory,
		createCoupon,
		updateCoupon
	} from "../api.js";
	export default {
		data() {
			return {
				couponType: [{
						value: 1,
						name: "满减卷"
					},
					{
						value: "",
						name: "全部"
					}
				],
				couponStatus: [{
						value: 0,
						name: "下架"
					},
					{
						value: 1,
						name: "正常"
					},
					{
						value: -1,
						name: "已过期"
					},
					{
						value: "",
						name: "全部"
					}
				],
				loading: true, //加载
				couponList: [], //优惠券list
				// 搜索
				total: 1, //总条数
				searList: { //搜索
					title: undefined,
					type: undefined,
					status: undefined,
					pageNo: 1,
					limit: 20,
				},
				title: '创建', //弹框标题
				dialogVisible: false, //弹框
				couponForm: { //表单
					id: "",
					title: "",
					type: 1,
					description: "",
					total: 0,
					discount: 0,
					limit: 0,
					min: 0,
					status: 1,
					tag: "",
					categoryId: "",
					categoryTitle: "",
					goodsType: 0,
					goodsValue: "",
					timeType: 1,
					days: "",
					gmtStart: "",
					gmtEnd: ""
				},
				rules: {
					title: [{
						required: true,
						message: "优惠券标题不能为空",
						trigger: "blur"
					}],
					type: [{
						required: true,
						message: "优惠券类型不能为空",
						trigger: "blur"
					}],
					total: [{
							required: true,
							message: "优惠券总量不能为空",
							trigger: "blur"
						},
						{
							pattern: /^[0-9]*$/,
							message: "请输入整数"
						}
					],
					limit: [{
							required: true,
							message: "优惠券限领不能为空",
							trigger: "blur"
						},
						{
							pattern: /^[0-9]*$/,
							message: "请输入整数"
						}
					],
					discount: [{
							required: true,
							message: "优惠券折扣金额不能为空",
							trigger: "blur"
						},
						{
							pattern: /^[0-9]*$/,
							message: "请输入整数"
						}
					],
					min: [{
							required: true,
							message: "优惠券使用门栏不能为空",
							trigger: "blur"
						},
						{
							pattern: /^[0-9]*$/,
							message: "请输入整数"
						}
					],
					status: [{
						required: true,
						message: "优惠券状态不能为空",
						trigger: "blur"
					}]
				},
				couponTypeOptions: [{
					value: 1,
					name: "满减卷"
				}],
				couponStatusOptions: [{
						value: 1,
						name: "正常"
					},
					{
						value: 0,
						name: "下架"
					}
				],
				categoryOptions: [],
			}
		},
		methods: {
			// 获取数据
			getData() {
				this.loading = true;
				getCoupon(this.searList).then((res) => {
					console.log(res.data.data)
					res.data.data.items.forEach(item => {
						var now = new Date();
						if (item.gmtEnd < now) {
							item.status = -1;
						}
					});
					this.couponList = res.data.data.items;
					this.total = res.data.data.total;
					this.loading = false;
				})
			},
			handleSizeChange(val) { //每页条数
				this.searList.limit = val
				this.getData();
			},
			handleCurrentChange(val) { //前往第几页
				this.searList.pageNo = val
				// console.log(val)
				this.getData()
			},
			// 搜索
			search() {
				this.searList.pageNo = 1;
				this.getData();
			},
			// 状态
			statusFitlters(value) {
				// console.log(value)
				if (value == 1) {
					return "正常";
				} else if (value == 0) {
					return "下架";
				} else if (value < 0) {
					return "已过期";
				} else {
					return "错误状态";
				}
			},
			// 领劵开始时间
			startTime(value) {
				if (value) {
					var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
					var F = date.getFullYear();
					var M = date.getMonth() + 1 + '-';
					var D = date.getDate() + '-';
					var h = date.getHours() + ':';
					var m = date.getMinutes() + ':';
					var s = date.getSeconds();
					return F + M + D + h + m + s;
				} else {
					return '无'
				}
			},
			// 领劵结束时间
			endTime(value) {
				if (value) {
					var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
					var F = date.getFullYear();
					var M = date.getMonth() + 1 + '-';
					var D = date.getDate() + '-';
					var h = date.getHours() + ':';
					var m = date.getMinutes() + ':';
					var s = date.getSeconds();
					return F + M + D + h + m + s;
				} else {
					return '无'
				}
			},
			// 按钮状态
			statusBtn(value) {
				if (value === 1) {
					return "冻结";
				} else if (value === 0) {
					return "激活";
				} else if (value < 0) {
					return "已过期";
				} else {
					return "错误状态";
				}
			},
			// 设置优惠券状态
			setStatus(value) {
				this.couponForm = Object.assign({}, value);
				this.couponForm.status = this.couponForm.status === 1 ? 0 : 1; //
				setCouponStatus(this.couponForm).then((res) => {
					// console.log(res);
					this.$message.success("修改优惠券成功");
					value.status = value.status === 1 ? 0 : 1;
				})
				// 优惠卷已经过期时
				if (value.status < 0) {
					this.$message.error("过期优惠卷，建议删除");
					return false;
				}
			},
			// 删除优惠券
			delCoupon(value) {
				console.log(value)
				this.$confirm("此操作将永久删除该优惠卷" + value.title + ", 是否继续?",
					"提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					}
				).then(() => {
					deleteCoupon(value).then((res) => {
						// console.log(res)
						this.$message.success("删除优惠券成功");
						let index = this.couponList.indexOf(value);
						this.couponList.splice(index, 1);
					})
				})
			},
			// 初始化表单
			fixCoupon(type, value) {
				this.dialogVisible = true;
				this.getCategoryTree();
				if (type === 'add') {
					this.title = '创建'
					this.couponForm = {
						id: "",
						title: "",
						desc: "",
						tag: "",
						total: 0,
						discount: 0,
						min: 0,
						limit: 0,
						status: 1,
						type: 1,
						goodsType: 0,
						goodsValue: "",
						timeType: 0,
						days: "",
						categoryId: "",
						categoryTitle: "",
						gmtStart: "",
						gmtEnd: ""
					}
				} else {
					this.title = '查看'
					this.couponForm = Object.assign({}, value);
					// console.log(this.couponForm.timeType,this.couponForm.days);
					// 判断时间是相对时间还是绝对时间
					if (this.couponForm.days === undefined || this.couponForm.days === 0) {
						this.couponForm.timeType = 1;
					} else {
						this.couponForm.timeType = 0;
					}
					if (this.couponForm.categoryId === "" || this.couponForm.categoryId == "") {
						this.couponForm.goodsType = 0;
					} else {
						this.couponForm.goodsType = 1;
					}
				}
				// 清空表单验证
				if (this.$refs.couponForm != undefined) {
					this.$refs.couponForm.resetFields(); //form表单的dom渲染完在执行this.$refs.couponForm.resetFields()，去除验证
				}
			},
			// 添加优惠劵
			addCoupon(formName) {
				let _this = this
				// 时间没填写时
				if (_this.couponForm.days === "" && (_this.couponForm.gmtStart === "" || _this.couponForm.gmtEnd === "")) {
					// console.log(_this.couponForm.gmtStart === "" || _this.couponForm.gmtEnd == "")
					this.$message.error("请填写优惠卷使用区间息");
					return;
				}
				if (_this.couponForm.timeType === 0) {
					_this.couponForm.gmtStart = undefined;
					_this.couponForm.gmtEnd = undefined;
					if (_this.couponForm.days === "" || _this.couponForm.days === "0") {
						_this.$message.error("请正确填写时长,不能为空或为0");
						return;
					}
				} else {
					_this.couponForm.days = undefined;
					if (_this.couponForm.gmtStart > _this.couponForm.gmtEnd) {
						_this.$message.error("请选择正确的日期");
						return;
					} else if (_this.couponForm.gmtStart === "" || _this.couponForm.gmtEnd === "") {
						// console.log(123)
						_this.$message.error("请填写优惠卷使用区间息");
						return;
					}
					_this.couponForm.gmtStart = new Date(_this.couponForm.gmtStart).getTime(); //转为时间戳
					_this.couponForm.gmtEnd = new Date(_this.couponForm.gmtEnd).getTime();
				}
				// 全场通用
				if (_this.couponForm.goodsType === 0) {
					_this.couponForm.categoryId = undefined;
				}
				// 判定满减门栏与折扣金额
				if (_this.couponForm.discount > _this.couponForm.min) {
					_this.$message.error("满减门栏不能低于折扣金额,但是可以等于");
					return;
				}
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// console.log(_this.couponForm)
						_this.couponForm.discount = _this.couponForm.discount * 100;
						_this.couponForm.min = _this.couponForm.min * 100;
						createCoupon(_this.couponForm).then((res) => {
							// console.log(res)
							if (res.data.errno === 200) {
								_this.dialogVisible = false;
								_this.$message.success("更新优惠券成功");
								_this.getData()
							} else {
								_this.dialogVisible = false;
								_this.$message.error(res.data.errmsg);
								_this.getData()
							}
						})
					} else {
						return false;
					}
				})
			},
			// 编辑优惠券
			updateData(formName) {
				let _this = this;
				if (_this.couponForm.timeType === 0) {
					_this.couponForm.gmtStart = undefined;
					_this.couponForm.gmtEnd = undefined;
					if (_this.couponForm.days === "" || _this.couponForm.days === "0") {
						_this.$message.error("请正确填写时长,不能为空或为0");
						return;
					}
				} else {
					_this.couponForm.days = undefined;
					if (_this.couponForm.gmtStart > _this.couponForm.gmtEnd) {
						_this.$message.error("请选择正确的日期");
						return;
					} else if (_this.couponForm.gmtStart === "" || _this.couponForm.gmtEnd === "") {
						// console.log(123)
						_this.$message.error("请填写优惠卷使用区间息");
						return;
					}
					_this.couponForm.gmtStart = new Date(_this.couponForm.gmtStart).getTime(); //转为时间戳
					_this.couponForm.gmtEnd = new Date(_this.couponForm.gmtEnd).getTime();
				}
				_this.$refs[formName].validate((valid) => {
					if (valid) {
						console.log(_this.couponForm)
						updateCoupon(_this.couponForm).then((res) => {
							console.log(res)
							if (res.data.errno == 200) {
								_this.dialogVisible = false;
								_this.$message.success('更新角色成功!')
								_this.getData()
							} else {
								_this.dialogVisible = false;
								_this.$message.error(res.data.errmsg);
								_this.getData()
							}
						})
					} else {

					}
				})
			},
			// 获取类目树
			getCategoryTree() {
				if (this.categoryOptions.length === 0) {
					getCategory().then(res => {
						this.categoryOptions = res.data.data;
					});
				}
			},
			// 关闭弹框
			closeDialog() {
				this.dialogVisible = false;
			},
			// 导出
			download() {
				// import('../../vendor/Export2Excel.js').then(excel => {
				//   excel.export_json_to_excel({
				//     header: ["优惠券ID",'名称','介绍','类型','最低消费','减免金额','每人限领','优惠券数量','剩余数量','状态','使用类目'], //表头 必填
				//     data:this.couponList, //具体数据 必填
				//     filename: 'excel-list', //非必填
				//     autoWidth: true, //非必填
				//     bookType: 'xlsx' //非必填
				//   })
				// })

				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('../../vendor/Export2Excel.js') //这里根据具体路径来修改
					const tHeader = ["优惠券ID", '名称', '介绍', '类型', '最低消费', '减免金额', '每人限领', '优惠券数量', '剩余数量', '状态', '使用类目']
					const filterVal = ["id", "title", "description", "type", "min", "discount", "limit", "total", "surplus",
						"status", "cateotry"
					] //这是你从list中取哪些字段
					const list = this.couponList //后端返回的list
					// console.log(list)
					const data = this.formatJson(filterVal, list)
					export_json_to_excel(tHeader, data, '优惠券信息')
					// this.downloadLoading = false
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			}
		},
		created() {
			this.getData()
		}
	}
</script>

<style>
	.counpon_container {
		width: 100%;
		height: 660px;
		overflow-x: auto;
		overflow-y: auto;
	}

	.counpon_header>* {
		margin-left: 4px;
	}

	.counpon_section {
		width: 100%;
		height: 100%;
		padding: 20px;
		background-color: #fff;
	}

	.counpon_header {
		padding-bottom: 10px;
	}

	/* .el-scrollbar .el-scrollbar__wrap .el-scrollbar__view{
	   white-space: nowrap;
	} */
	.el-table__body-wrapper {
		overflow-y: hidden;
		overflow-x: auto;
	}

	.el-table__body-wrapper::-webkit-scrollbar {
		-webkit-appearance: none;
	}

	.el-table__body-wrapper::-webkit-scrollbar:vertical {
		width: 11px;
	}

	.el-table__body-wrapper::-webkit-scrollbar:horizontal {
		height: 18px;
	}

	.el-table__body-wrapper::-webkit-scrollbar-thumb {
		border: 2px solid #f1f1f1;
		/* should match background, can't be transparent */
		background-color: #a8a8a8;
	}
</style>
